package com.zh.work.controller.platform.agent;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.entity.Oauth;
import com.zh.work.dao.platform.agent.AgentInfoMapper;
import com.zh.work.dao.platform.agent.QrCodeAgentFeeMapper;
import com.zh.work.entity.agent.AgentInfoEntity;
import com.zh.work.entity.agent.QrCodeAgentFee;

import com.zh.work.service.platform.agent.AgentInfoService;
import com.zh.common.entity.JSONResult;
import com.zh.work.util.plateform.ServiceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.zh.common.annotaion.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 代理商管理
 * @Author: Li.HuiNeng
 * @Create in: 2019/08/28
 * @Version: 1.0.1
 */
@Api(value = "代理商管理控制器", produces = "application/json", tags = {"AgentInfo管理控制器"})
@RestController
@RequestMapping("/agentInfo")
public class AgentInfoController {

    private static final Logger log = LoggerFactory.getLogger(AgentInfoController.class);

    /**
     * @Description: 简易crud时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/08/28
     */
    @Autowired
    private AgentInfoMapper mapper;


    /**
     * @Description: 有业务逻辑需要处理时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/08/28
     */
    @Autowired
    private AgentInfoService agentInfoService;

    /**
     * @Description: 代理商二维码费率接口
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/11/23
     */
    @Autowired
    private QrCodeAgentFeeMapper codeAgentFeeMapper;

    /**
     * @Description: redis实例
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/08/28
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "新增一条记录", tags = {"putAddAgentInfo"}, notes = "新增一条记录")
    @PutMapping("/putAddAgentInfo")
    @ResponseBody
    public JSONResult putAddAgentInfo(@ApiParam(value = "代理商信息实体类", name = "agentInfoEntity") @RequestBody AgentInfoEntity agentInfoEntity) {
        JSONResult<AgentInfoEntity> jsonResult = new JSONResult<AgentInfoEntity>();
        try {
            int i = this.agentInfoService.putAgentInfo(agentInfoEntity);
            if (i > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setSuccess(false);
                ServiceUtil.msg(i, jsonResult);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "通过id修改信息", tags = {"putModAgentInfoById"}, notes = "通过id修改信息接口")
    @PutMapping("/putModAgentInfoById")
    @ResponseBody
    public JSONResult<AgentInfoEntity> putModAgentInfoById(@ApiParam(value = "代理商信息实体类", name = "agentInfoEntity")
                                                           @RequestBody AgentInfoEntity agentInfoEntity) {
        JSONResult<AgentInfoEntity> jsonResult = new JSONResult<AgentInfoEntity>();
        try {
            int i = agentInfoService.modAgentInfo(agentInfoEntity);
            if (i > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("修改完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setSuccess(false);
                if (i == -1) jsonResult.setMessage("二维码费率不能为空,请填写.");
                if (i == -2) jsonResult.setMessage("修改二维码费率信息失败.");
                if (i == -13) jsonResult.setMessage("修改代理商信息失败.");
                ServiceUtil.msg(i, jsonResult);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "代理商二维码费率设置", tags = {"putAddQrCodeAgentFee"}, notes = "代理商二维码费率设置")
    @PutMapping("/putAddQrCodeAgentFee")
    public JSONResult<QrCodeAgentFee> putAddQrCodeAgentFee(@ApiParam(value = "代理商费率实体类", name = "qrCodeAgentFee") QrCodeAgentFee qrCodeAgentFee) {
        JSONResult<QrCodeAgentFee> jsonResult = new JSONResult<QrCodeAgentFee>();
        try {
            if (qrCodeAgentFee.insert()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("添加失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


    @Transactional
    @ApiOperation(value = "根据主键删除记录", tags = {"deleteAgentInfoById"}, notes = "根据主键删除记录")
    @DeleteMapping("/deleteAgentInfoById")
    public JSONResult<Object> deleteAgentInfoById(@ApiParam(value = "代理商信息实体类", name = "agentInfoEntity") AgentInfoEntity agentInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Oauth auth = (Oauth) authentication.getPrincipal();
//        agentInfoEntity.setBranchNo(auth.getUserParentNo());
        try {
            // 删除关联关系表字段再删除代理商信息
            if (this.agentInfoService.delAgentAndUser(agentInfoEntity.getId()) <= 0) {
                jsonResult.setMessage("删除失败,请检查登录账号是否绑该代理商信息!");
                jsonResult.setSuccess(false);
                return jsonResult;
            }
            // 清除关联二维码费率信息
            try {
                // 删除指定代理商二维码费率信息
                this.codeAgentFeeMapper.delete(new LambdaQueryWrapper<QrCodeAgentFee>().eq(QrCodeAgentFee::getAgentNo, agentInfoEntity.getAgentNo()));
            } catch (Exception e) {
                jsonResult.setMessage("删除失败,二维码费率信息删除错误!");
                jsonResult.setSuccess(false);
                e.printStackTrace();
                return jsonResult;
            }
            if (agentInfoEntity.deleteById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @Transactional
    @ApiOperation(value = "根据主键列表批量删除记录", tags = {"deleteAgentInfoBatchByIds"}, notes = "该传参时 请选择raw(application/json)格式传入")
    @DeleteMapping("/deleteAgentInfoBatchByIds")
    @ResponseBody
    public JSONResult<Object> deleteAgentInfoBatchByIds(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            // 删除关联关系表字段再删除代理商信息
            for (int i = 0; i < ids.size(); i++) {
                if (this.agentInfoService.delAgentAndUser(Long.parseLong(ids.get(i).toString())) <= 0) {
                    jsonResult.setMessage("删除失败,请检查登录账号是否绑该代理商信息!");
                    jsonResult.setSuccess(false);
                    return jsonResult;
                }
            }
            int c = this.mapper.deleteBatchIds(ids);
            if (c > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据代理商编号查询详细信息", tags = {"getAgentInfoByAgentNo"}, notes = "根据代理商编号查询详细信息")
    @GetMapping("/getAgentInfoByAgentNo")
    public JSONResult<AgentInfoEntity> getAgentInfoByAgentNo(@ApiParam(value = "代理商信息实体类", name = "agentInfoEntity") AgentInfoEntity agentInfoEntity) {
        JSONResult<AgentInfoEntity> jsonResult = new JSONResult<AgentInfoEntity>();
        try {
            AgentInfoEntity result = this.mapper.selectOne(new LambdaQueryWrapper<AgentInfoEntity>()
                    .eq(AgentInfoEntity::getAgentNo, agentInfoEntity.getAgentNo()));
            if (result != null) {
                jsonResult.setCode(200);
                jsonResult.setMessage("查询完成");
                jsonResult.setSuccess(true);
                jsonResult.setData(result);
            } else {
                jsonResult.setMessage("未查询到相应信息，请检查参数是否正确");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "分页查询参数数据集", tags = {"getPagesAgentInfos"}, notes = "分页查询参数数据集")
    @GetMapping("/getPagesAgentInfos")
    public JSONResult<List<AgentInfoEntity>> getPagesAgentInfos(
            @ApiParam(value = "起始页", name = "pageNo") Integer pageNo,
            @ApiParam(value = "当前页显示数量", name = "pageNo") Integer pageSize,
            @ApiParam(value = "代理商信息实体类", name = "agentInfoEntity") AgentInfoEntity agentInfoEntity) {
        JSONResult<List<AgentInfoEntity>> jsonResult = new JSONResult<List<AgentInfoEntity>>();
        try {
            Page<AgentInfoEntity> page = new Page<>(pageNo, pageSize);
            IPage<AgentInfoEntity> result = this.agentInfoService.selectAgentPage(page, agentInfoEntity);
            jsonResult.setTotal(result.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "用于检查是否存在相同机构名称", tags = {"checkAgentByName"}, notes = "辅助方法,用于检查是否存在相同机构")
    @GetMapping("checkAgentByName")
    public JSONResult<Object> checkAgentByName(@ApiParam(value = "代理商名称", name = "agentName") @RequestParam("agentName") String agentName) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.agentInfoService.checkAgentByName(agentName);
            jsonResult.setSuccess(true);
            jsonResult.setData(i);
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取指定代理商费率信息", tags = {"getAgentParentFee"}, notes = "辅助方法,获取指定代理商费率信息")
    @GetMapping("getAgentParentFee")
    public JSONResult<List<QrCodeAgentFee>> getAgentParentFee(@ApiParam(value = "主键", name = "id") @RequestParam("id") String id) {
        JSONResult<List<QrCodeAgentFee>> jsonResult = new JSONResult<>();
        try {
            List<QrCodeAgentFee> list = this.agentInfoService.getAgentQrCodeRate(id);
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("未找到上级代理商费率信息!");

            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "代理商审核请求", tags = {"putAgentAudit"}, notes = "代理商请求接口,status: 2.审核拒绝,3.审核通过")
    @PutMapping("putAgentAudit")
    public JSONResult<Object> putAgentAudit(@ApiParam(value = "代理商id", name = "agentId") @RequestParam("agentId") String agentId,
                                            @ApiParam(value = "状态", name = "status") @RequestParam("status") Integer status,
                                            @ApiParam(value = "备注", name = "remark") @RequestParam(value = "remark", required = false) String remark) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.agentInfoService.modAgentStatus(agentId, remark, String.valueOf(status));
            if (i > 0) {
                jsonResult.setData(i);
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("抱歉,网络繁忙，请稍后再试!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("审核失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "获取代理二维码费率信息", tags = {"getAgentQrCodeRate"}, notes = "获取代理二维码费率信息")
    @GetMapping("getAgentQrCodeRate")
    public JSONResult<List<QrCodeAgentFee>> getAgentQrCodeRate(
            @ApiParam(value = "代理商号", name = "agentNo")
            @RequestParam("agentNo") String agentNo) {
        JSONResult<List<QrCodeAgentFee>> jsonResult = new JSONResult<>();
        try {
            List<QrCodeAgentFee> list = this.agentInfoService.getAgentQrCodeRate(agentNo);
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取指定代理商二维码费率失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @CurieCache
    @ApiOperation(value = "获取代理商列表", tags = {"getAgentList"}, notes = "获取代理商列表")
    @GetMapping("getAgentList")
    public JSONResult<List<AgentInfoEntity>> getAgentList() {
        JSONResult<List<AgentInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<AgentInfoEntity> list = this.agentInfoService.getAgentList();
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取代理商列表信息失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @CurieCache
    @ApiOperation(value = "获取指定级别的代理商列表信息", tags = {"getAgentListByLevel"}, notes = "获取指定级别的代理商列表信息")
    @GetMapping("getAgentListByLevel")
    public JSONResult<List<AgentInfoEntity>> getAgentListByLevel(@ApiParam(value = "代理商级别", name = "agentLevel")
                                                                 @RequestParam(value = "agentLevel", required = false) Integer agentLevel) {
        JSONResult<List<AgentInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<AgentInfoEntity> list = this.agentInfoService.getAgentListByLevel(agentLevel, null);
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取指定级别的代理商列表信息失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取指定机构下的代理商列表信息", tags = {"getAgentListByBranchNo"}, notes = "获取指定机构下的代理商列表信息")
    @GetMapping("getAgentListByBranchNo")
    public JSONResult<List<AgentInfoEntity>> getAgentListByBranchNo(@ApiParam(value = "机构编号", name = "branchNo") @RequestParam("branchNo") String branchNo) {
        JSONResult<List<AgentInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<AgentInfoEntity> list = this.agentInfoService.getAgentListByBranchNo(branchNo);
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取指定机构下的代理商列表信息失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


}
